package com.zb.frame.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zb.frame.modules.sys.entity.RelRoleMenu;
import com.zb.frame.modules.sys.mapper.RelRoleMenuMapper;
import com.zb.frame.modules.sys.service.RelRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bangZZ
 * @since 2020-06-04
 */
@Service
public class RelRoleMenuServiceImpl extends ServiceImpl<RelRoleMenuMapper, RelRoleMenu> implements RelRoleMenuService {

    @Autowired
    RelRoleMenuMapper roleMenuMapper;

    @Override
    public boolean isExistRole(String roleId) {
        QueryWrapper<RelRoleMenu> wrapper = new QueryWrapper<RelRoleMenu>();
        wrapper.eq("role_id", roleId);
        return this.count(wrapper) > 0;
    }

    @Override
    public boolean addRelBatch(List<RelRoleMenu> list) {
        System.out.println(JSON.toJSONString(list));
        return this.saveBatch(list);
    }

    @Override
    public boolean deleteByMenuId(Long menuId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("menu_id", menuId);
        return this.remove(wrapper);
    }

    @Override
    public boolean deleteByRoleIdAndMenuIds(String roleId, List<Long> menuIds) {
        System.out.println(JSON.toJSONString(menuIds));
        Map<String, Object> params = new HashMap<>();
        params.put("roleId", roleId);
        params.put("menuIds", menuIds);
        return roleMenuMapper.deleteByRoleIdAndMenuIds(params) > 0;
    }

    @Override
    public List<String> getRolesByMenuId(Long menuId) {
        List<String> ret = new ArrayList<>();
        List<RelRoleMenu> list = roleMenuMapper.getRolesByMenuId(menuId);
        for (RelRoleMenu obj : list) {
            ret.add(obj.getRoleName());
        }
        return ret;
    }

    @Override
    public List<Long> getMenusByRoleId(String roleId) {
        List<Long> ret = new ArrayList<>();
        QueryWrapper<RelRoleMenu> wrapper = new QueryWrapper<RelRoleMenu>().select("menu_id");
        wrapper.eq("role_id", roleId);
        List<RelRoleMenu> list = this.list(wrapper);
        for (RelRoleMenu obj : list) {
            ret.add(obj.getMenuId());
        }
        return ret;
    }
}
